<template>
	<div class="search-div">
		<el-form label-width="70px" size="small" :inline="true">
            <!-- {{value1}} -->



			<el-form-item label="关键字">
				<el-input
					placeholder="用户名、姓名、手机号码"
					v-model="sysUserDto.keyword"
				></el-input>
			</el-form-item>


	

            <el-form-item label="创建时间">
				<el-date-picker
                    v-model="value1"
                    type="daterange"
                    value-format="YYYY-MM-DD"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    :size="size"
                />
			</el-form-item>

			<el-row style="display:flex">
				<el-button type="primary" size="small" @click="fetchData">
					搜索
				</el-button>
				<el-button size="small" @click="reset">重置</el-button>
			</el-row>
		</el-form>

		<!-- 添加按钮 -->
		<div class="tools-div">
			<el-button type="success" size="small" @click="addShow">添 加</el-button>
		</div>

		<el-dialog
			v-model="dialogVisible"
			title="添加/修改"
			width="50%"
		>	{{sysUser}}
			<el-form label-width="70px" size="small">
				<el-form-item label="账号">
					<el-input
						style="width: 100%"
						placeholder="账号"
						v-model="sysUser.userName"
					></el-input>
				</el-form-item>
				<el-form-item label="密码">
					<el-input
						style="width: 100%"
						placeholder="密码"
						v-model="sysUser.password"
					></el-input>
				</el-form-item>
				<el-form-item label="姓名">
					<el-input
						style="width: 100%"
						placeholder="姓名"
						v-model="sysUser.name"
					></el-input>
				</el-form-item>

				<el-form-item label="手机号">
					<el-input
						style="width: 100%"
						placeholder="手机号"
						v-model="sysUser.phone"
					></el-input>
				</el-form-item>
				<el-form-item label="描述">
					<el-input
						style="width: 100%"
						placeholder="描述"
						v-model="sysUser.description"
					></el-input>
				</el-form-item>

				<el-form-item label="头像">
					<!-- 选中一个文件之后，自动调用该接口，此时并不是通过request.js去调用的 -->
					<!-- 那么request.js中的请求拦截器没有，所以请求头就没有token，所以显示用户未登录 -->
					<!-- 让文件上传控件，传递一个请求头 -->
					<!-- on-success : 文件上传接口调用成功之后，要执行的函数 -->
					<el-upload
						class="avatar-uploader"
						action="http://localhost:8501/admin/system/upload/upload"
						:headers="mytoken"
						:on-success="handleAvatarSuccess"
					>
						<!-- 如果该属性不为空，则建立img标签 -->
						<img v-if="sysUser.avatar" :src="sysUser.avatar" class="avatar" width="150"  />
						<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
					</el-upload>
				</el-form-item>


				<el-row style="display:flex">
					<el-button type="primary" size="small" @click="submitDialog" >
						提交
					</el-button>
				</el-row>
			</el-form>
			
		</el-dialog>


		<el-dialog
			v-model="assignRoleDialogVisible"
			title="分配角色"
			width="50%"
		>	 {{roleIdList}}
			<el-form label-width="70px" size="small">
				
				<el-form-item label="用户名">
					<el-input
						style="width: 100%"
						placeholder="用户名"
						readonly
						v-model="sysUser.userName"
					></el-input>
				</el-form-item>

				<el-form-item label="角色列表">
					
					<!-- roleIdList： 用于存储选中的复选框的id值 -->
					<el-checkbox-group v-model="roleIdList">
						<!-- 对角色集合进行遍历，每个角色对一个复选框 -->
						<!-- :label="role.id"   选中某个复选框后将其值存储到 -->
						<!-- 复选框的回显, roleIdList数组中存在哪些角色id，对应的复选框就默认被选中 -->
						<!-- 例如：roleIdList  = [ 39 , 40]    -->
						<!-- 每个复选框的key就是id值，  key=39  和  key=40的复选框默认被选中 -->
						<el-checkbox v-for="role in roleList" :label="role.id" :key="role.id" >
							{{role.roleName}}
						</el-checkbox>
					</el-checkbox-group>

				</el-form-item>
				
				<el-row style="display:flex">
					<el-button type="primary" size="small" @click="submitAssignRoleDialog" >
						提交
					</el-button>
					<el-button type="default" size="small" >
						取消
					</el-button>
				</el-row>
			</el-form>
			
		</el-dialog>

		<!--- 角色表格数据 -->
		<el-table :data="list" style="width: 100%">
			<!-- roleName ，roleCode 。。。  json中的属性名 -->
			<el-table-column prop="userName" label="账号" width="180" />
			<el-table-column prop="name" label="昵称" width="180" />

			<el-table-column label="头像" #default='scope'>
                <img :src="scope.row.avatar" width="50" >
            </el-table-column>

			<el-table-column prop="description" label="描述" />

			<el-table-column label="状态" #default="scope">
				{{ scope.row.status == 1 ? '正常' : '禁用' }}
			</el-table-column>

            <el-table-column prop="createTime" label="创建时间" />

			<el-table-column label="操作" align="center" width="280" #default="scope">
				<el-button type="primary" size="small" @click="editShow(scope.row)">
					修改
				</el-button>
				<el-button type="danger" size="small" @click="deleteById(scope.row.id)">
					删除
				</el-button>
				<el-button type="danger" size="small" @click="showAssignRoleDialog(scope.row)">
					分配角色
				</el-button>
			</el-table-column>
		</el-table>

		<el-pagination
			v-model:current-page="pageParam.pageNum"
			v-model:page-size="pageParam.pageSize"
			:page-sizes="[1, 2, 3, 5]"
			layout="total, sizes, prev, pager, next, jumper"
			:total="total"
			@size-change="fetchData"
			@current-change="fetchData"
		/>
	</div>
</template>

<script setup>
	import { ref, onMounted } from 'vue'

	import { FindByPage,AddUser ,EditUser ,DeleteUser} from '@/api/sysUser'
	import { FindAllRoleAndRoleIdList,DoAssign } from '@/api/sysRole'

	import { ElMessage,ElMessageBox } from 'element-plus'

	//文件上传控件传递的请求头
	let mytoken = {
		token: JSON.parse(window.localStorage['VEA-TOKEN']).token
	}

	//文件上传接口调用成功后的函数
	let handleAvatarSuccess = (response,uploadFile)=>{
		console.log(response)
		sysUser.value.avatar = response.data
	}


	let list = ref([])
	let pageParam = ref({
		pageNum: 1,
		pageSize: 3,
	})
	let sysUserDto = ref({
		keyword: '',
		createTimeBegin: '',
		createTimeEnd: '',
	})
	let total = ref(0)

    let value1 = ref([])

	onMounted(() => {
		fetchData()
	})

	let fetchData = async () => {

        //判断时间数组的长度,如果长度=2，取出两个日期赋值给sysUserDto的createTimeBegin和createTimeEnd
        if(value1.value.length==2){
            sysUserDto.value.createTimeBegin = value1.value[0]
            sysUserDto.value.createTimeEnd = value1.value[1]
        }

		let { data } = await FindByPage(
			pageParam.value.pageNum,
			pageParam.value.pageSize,
			sysUserDto.value
		)
		list.value = data.list
		total.value = data.total
	}

	let reset = () => {
		sysUserDto.value = {
			keyword: '',
			createTimeBegin: '',
			createTimeEnd: '',
		}
		pageParam.value = {
			pageNum: 1,
			pageSize: 3,
		}
        value1.value = []
        fetchData()
	}

	//弹窗上控件绑定的对象以及属性
	let sysUser = ref({
		// username:'', json中的属性名可以不用去声明，控件直接绑定就可以
		// password:'',
	})

	let dialogVisible = ref(false)//控制弹窗是否显示

	//添加按钮
	let addShow = ()=>{
		sysUser.value = {}
		dialogVisible.value = true
	}

	//弹窗上的提交按钮
	let submitDialog = async ()=>{
		//添加和修改使用同一个弹窗，同一个提交按钮
		if(sysUser.value.id){
			//修改
			let {code,message} = await EditUser(sysUser.value)
			if(code==200){
				ElMessage.success('修改成功')
				dialogVisible.value = false
				fetchData()
			}else{
				ElMessage.warning('修改失败,' + message)
			}


		}else{
			//添加
			let {code,message} = await AddUser(sysUser.value)
			if(code==200){
				ElMessage.success('添加成功')
				dialogVisible.value = false
				fetchData()
			}else{
				ElMessage.warning('添加失败,' + message)
			}
			
		}
	}

	//修改按钮绑定的方法
	let editShow = (row)=>{
		sysUser.value = row
		dialogVisible.value = true
	}

	//删除按钮
	let deleteById = async (id)=>{
		let {code} = await DeleteUser(id)
		if(code==200){
			ElMessage.success('删除成功')
			fetchData()
		}else{
			ElMessage.warning('删除失败')
		}
	}

	//控制分配角色弹窗是否打开
	let assignRoleDialogVisible = ref(false)
	//点击分配角色按钮时需要调用的方法
	let showAssignRoleDialog = (row)=>{
		assignRoleDialogVisible.value = true
		sysUser.value = row
		findRoleList() //查询弹窗上遍历的角色列表，还有当前用户已分配的角色id列表
	}

	//roleIdList（复选框绑定到该集合上）
	let roleIdList = ref([])

	//角色列表
	let roleList = ref([
		{id:9,roleName:'平台管理员'},
		{id:10,roleName:'超级管理员'},
	])

	//查询所有角色
	let findRoleList = async ()=>{
		let {data} = await FindAllRoleAndRoleIdList(sysUser.value.id)
		roleList.value = data.roleList
		roleIdList.value = data.roleIdList
	}

	//分配角色弹窗上的提交按钮
	let submitAssignRoleDialog = async ()=>{
		//接口参数
		let assginRoleDto = {userId:sysUser.value.id,roleIdList:roleIdList.value}

		let {code,message} = await DoAssign(assginRoleDto)
		if(code==200){
			ElMessage.success("分配成功")
			assignRoleDialogVisible.value = false
		}else{
			ElMessage.warning('分配失败' + message)
		}
	}


	// let imageUrl = ref('http://192.168.188.128:9000/spzx-bucket/2024/02/23/f0bf8e2c1c3d4a74a050b326777a821e1.png')

</script>

<style scoped>
	.search-div {
		margin-bottom: 10px;
		padding: 10px;
		border: 1px solid #ebeef5;
		border-radius: 3px;
		background-color: #fff;
	}

	.tools-div {
		margin: 10px 0;
		padding: 10px;
		border: 1px solid #ebeef5;
		border-radius: 3px;
		background-color: #fff;
	}
</style>